package xupt.se.ttms.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import xupt.se.ttms.dao.UserDAO;
import xupt.se.ttms.model.User;

@WebServlet("/user/UpdateHead")
public class UpdateHead extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

        // 创建该对象
        DiskFileItemFactory dff = new DiskFileItemFactory();
        // 设置在内存中的缓冲大小
        dff.setSizeThreshold(1024 * 1000);
        // 创建上传对象
        ServletFileUpload sfu = new ServletFileUpload(dff);
        // 指定单个上传文件的大小不超过2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        String fp = "";
        try
        {

            List<FileItem> items = sfu.parseRequest(request);
            for(FileItem file : items)
            {
                // 是文件
                if(!file.isFormField())
                {

                    String fname = file.getName().substring(file.getName().lastIndexOf("\\") + 1);
                    File file2 = new File(getServletContext().getRealPath("/"));
                    File newfile = new File(file2 + "/" + fname);
                    file.write(newfile);
                    fp = file.getName();
                }
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        // 更改图片路径
        UserDAO userDAO = new UserDAO();
        User user = (User) request.getSession().getAttribute("user");
        if(null != fp && !"".equals(fp))
        {
            user.setPath(fp);
            userDAO.updateHead(user);
        }
       
        request.getRequestDispatcher("/user/info.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

}
